package com.jackrain.nea.fc.cp.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.CadorgSaveCmd;
import com.jackrain.nea.fc.cp.adutils.AdOrganization;
import com.jackrain.nea.fc.cp.mapper.CadorgMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;
import java.sql.Timestamp;
import java.util.HashMap;


/**
 * Created by ZCY on 2017/12/14.
 * AD域组织
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class CadorgSaveCmdImpl extends CommandAdapter implements CadorgSaveCmd {
    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH-mm-ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (param == null) {
            throw new NDSException("请选择需要同步的组织！");
        }
        CadorgMapper cadorgMapper = ApplicationContextHandle.getBean(CadorgMapper.class);
        JSONArray Idsary = param.getJSONArray("IDS");
        Boolean idsbol = Idsary == null || (Idsary != null && Idsary.size() == 0);
        if (idsbol) {
            throw new NDSException("请传入组织IDS数组");
        }
        String type = param.getString("TYPE");
        if (StringUtils.isEmpty(type)) {
            throw new NDSException("请传入组织类型");
        }
        String orgtype = null;
        if (type.equals("ORG")) {
            orgtype = "wWWHomePage";
        } else {
            orgtype = "telephoneNumber";
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        JSONArray dataary = new JSONArray();
        AdOrganization.ldapload();
        Boolean backbol = true;
        for (int i = 0; i < Idsary.size(); i++) {
            Long objid = Idsary.getLong(i);
            Long orgid = objid;
            String orgname = null;
            HashMap orghash = null;
            JSONObject result = new JSONObject(true);
            String isactive = null;
            try {
                if ("ORG".equals(type)) {
                    //组织的
                    orghash = cadorgMapper.findorgin(orgid);
                    if (orghash == null) {
                        orgname = objid.toString();
                        throw new NDSException("组织ID=" + objid + "的当前记录已不存在");
                    } else {
                        orgname = TypeUtils.castToString(orghash.get("ENAME"));
                    }
                    isactive = TypeUtils.castToString(orghash.get("ISACTIVE"));
                    if ("Y".equals(isactive)) {
                        result = travlorg(orgid, orgtype, orgname, null);
                    }

                } else {
                    //门店档案的
                    orghash = cadorgMapper.findstore(orgid);
                    if (orghash == null) {
                        orgname = objid.toString();
                        throw new NDSException("ID=" + objid + "该门店档案记录已不存在");
                    }
                    orgname = TypeUtils.castToString(orghash.get("ENAME"));
                    if (StringUtils.isEmpty(orgname)) {
                        orgname = objid.toString();
                        throw new NDSException("ID=" + objid + "该门店名称为空");
                    }
                    Long hrogid = TypeUtils.castToLong(orghash.get("CP_C_HRORG_ID"));
                    if (hrogid == null) {
                        throw new NDSException("该门店所属组织为空");
                    }
                    isactive = TypeUtils.castToString(orghash.get("ISACTIVE"));
                    if ("Y".equals(isactive)) {
                        result = travlorg(hrogid, orgtype, orgname, objid);
                    }
                }
                if ("Y".equals(isactive)) {
                    JSONObject huserobj = result.getJSONObject("org");
                    huserobj.put(orgtype, objid);
                    JSONObject groupobj = result.getJSONObject("group");
                    AdOrganization.getOrg(huserobj, orgtype, groupobj);
                    JSONObject successobj = new JSONObject(true);
                    successobj.put("org", orgname);
                    dataary.add(successobj);
                } else {
                    JSONObject userobj = new JSONObject(true);
                    userobj.put(orgtype, objid);
                    AdOrganization.delorg(userobj, orgtype);
                    JSONObject suobj = new JSONObject(true);
                    suobj.put("org", orgname);
                    dataary.add(suobj);
                }
            } catch (Exception e) {
                JSONObject exobj = new JSONObject(true);
                exobj.put("org", orgname);
                exobj.put("error", e.getMessage());
                dataary.add(exobj);
                backbol = false;
            }
        }

        if (backbol) {
            vh.put("code", 0);

        } else {
            vh.put("code", -1);
        }
        vh.put("message", dataary);
        AdOrganization.closeCtx();
        return vh;

    }

    //查找上级组织
    public JSONObject travlorg(Long orgid, String type, String Storename, Long storeid) {


        Storename=Storename.replaceAll("[/\\\\]","|");

        CadorgMapper cadorgMapper = ApplicationContextHandle.getBean(CadorgMapper.class);
        StringBuffer hrogbuf = new StringBuffer("");
        Boolean adexist = true;
        Integer i = 0;
        JSONObject groupobj = new JSONObject(true);
//        orgtype="aCSPolicyName"
        if (type.equals("telephoneNumber")) {
            hrogbuf.append("OU=").append(Storename).append(",");
            String strname = Storename + (i++);
            groupobj.put(strname, storeid);
        }
        do {

            HashMap horoghash = cadorgMapper.findorgin(orgid);
            if (horoghash == null) {
                throw new NDSException("组织ID="+orgid+"当前记录已不存在！");
            }
            Long CpcOrgupid = TypeUtils.castToLong(horoghash.get("CP_C_ORGUP_ID"));
            String horgEname = TypeUtils.castToString(horoghash.get("ENAME"));
            horgEname=horgEname.replaceAll("[/\\\\]","|");
            hrogbuf.append("OU=").append(horgEname).append(",");
            groupobj.put(horgEname + (i++), orgid);
            if (CpcOrgupid == null) {
                adexist = false;
                break;
            }

            orgid = CpcOrgupid;
        } while (adexist);
//        log.info(hrogbuf + "====orgbuf====");
        hrogbuf.deleteCharAt(hrogbuf.length() - 1);
        
        String strhrorg = hrogbuf.toString();

        strhrorg=strhrorg.replaceAll("[/\\\\]","|");


        JSONObject huserobj = new JSONObject(true);
        huserobj.put("ou", Storename);
        huserobj.put("ORGLINK", strhrorg);

        JSONObject result = new JSONObject(true);
        result.put("group", groupobj);
        result.put("org", huserobj);
        return result;

    }
}
